package com.mars.foodserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.foodserver.entity.FoodNotes;
import com.mars.foodserver.entity.User;
import com.mars.foodserver.mapper.FoodNotesMapper;
import com.mars.foodserver.response.FoodNotesResponse;
import com.mars.foodserver.response.base.BasePageRequest;
import com.mars.foodserver.response.base.PageInfo;
import com.mars.foodserver.service.IFoodNotesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mars.foodserver.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-07-21
 */
@Service
public class FoodNotesServiceImpl extends ServiceImpl<FoodNotesMapper, FoodNotes> implements IFoodNotesService {

    @Resource
    private IUserService userService;

    @Override
    public void createNotes(Integer userId, String notes, String image) {
        FoodNotes foodNotes = new FoodNotes();
        foodNotes.setNotes(notes);
        foodNotes.setImage(image);
        foodNotes.setUserId(userId);
        save(foodNotes);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public List<FoodNotes> listNotes() {

        LambdaQueryWrapper<FoodNotes> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(FoodNotes::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public PageInfo<FoodNotesResponse> page(BasePageRequest request) {
        IPage<FoodNotes> page = new Page<>(request.getPageNumber(), request.getPageSize());
        LambdaQueryWrapper<FoodNotes> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(FoodNotes::getCreateTime);
        List<FoodNotes> records = baseMapper.selectPage(page, wrapper).getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<FoodNotesResponse> list = records.stream().map(x -> {
                FoodNotesResponse response = new FoodNotesResponse();
                BeanUtils.copyProperties(x, response);
                User user = userService.selectById(x.getUserId());
                if (Objects.nonNull(user)) {
                    response.setUsername(user.getNickname());
                }
                return response;
            }).collect(Collectors.toList());
            return new PageInfo<>(page.getTotal(), list);
        }
        return null;
    }
}
